<?php
declare(strict_types=1);

namespace App\Wxc\Controller\SharerMp\V1;

use App\System\Request\UploadRequest;
use App\System\Service\SystemUploadFileService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Mine\Annotation\Auth;
use Mine\Middlewares\CheckModuleMiddleware;
use Mine\MineController;
use Psr\Http\Message\ResponseInterface;

/**
 * 文件管理
 */
#[Controller(prefix: "wxc/sharer-mp/v1/file-manager"), Auth('wxc_sharer_mp')]
#[Middleware(middleware: CheckModuleMiddleware::class)]
class FileManagerController extends MineController
{
    #[Inject]
    protected SystemUploadFileService $uploadFileService;


    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    /**
     * 文件上传
     */
    #[PostMapping("upload")]
    public function upload(RequestInterface $req): ResponseInterface
    {
        $sysUploadReq = container()->get(UploadRequest::class);
        $param = $req->all();
        if ($req->hasFile('image')) {
            $key = 'image';
            $rules = $sysUploadReq->uploadImageRules();
            $param['image'] = $req->file('image');
        } else {
            $key = 'file';
            $rules = $sysUploadReq->uploadFileRules();
            $param['file'] = $req->file('file');
        }
        $v = $this->validationFactory->make($param, $rules);
        if ($v->fails()) {
            return $this->error($v->errors()->first());
        }
        if ($req->file($key)->isValid()) {
            $data = $this->uploadFileService->upload($req->file($key), $req->all());
            if (empty($data)) {
                return $this->error('上传失败');
            }

            return $this->success('ok', ['url' => get_file_url($data['url'])]);
        }

        return $this->error('文件异常');
    }
}
